# 谢尔宾斯基三角形
import math
import turtle


# 画三角形
def drawTriangle(*pos):
    turtle.penup()
    turtle.goto(pos[0])
    turtle.pendown()
    for i in [1, 2, 0]:
        turtle.goto(pos[i])


# 获取两点中间坐标
def getMidPos(p1, p2):
    return (p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2


# 入参为三角形三个点的初始坐标
def sierpinski(*pos):
    p1 = pos[0]
    p2 = pos[1]
    p3 = pos[2]
    drawTriangle(p1, p2, p3)
    border = math.fabs((p3[0] - p1[0]) / 2)
    if border > 10:
        # p1和p2的中点
        p1_p2_center = (getMidPos(p1, p2))
        # p2和p3的中点
        p2_p3_center = (getMidPos(p2, p3))
        # p3和p1的中点
        p3_p1_center = (getMidPos(p3, p1))
        # 绘制左下角三角形
        sierpinski(p1, p1_p2_center, p3_p1_center)
        # 绘制上方三角形
        sierpinski(p1_p2_center, p2, p2_p3_center)
        # 绘制右下角三角形
        sierpinski(p3_p1_center, p2_p3_center, p3)


def main():
    turtle.title("谢尔宾斯基三角形")
    turtle.setup(900, 600, 200, 100)
    turtle.pensize(2)
    turtle.tracer(2)
    turtle.hideturtle()
    # turtle.speed(0)
    sideLength = 400
    p1 = (-sideLength / 2, -100)
    p2 = (0, sideLength / 2 * math.sqrt(3) - 100)
    p3 = (sideLength / 2, -100)
    sierpinski(p1, p2, p3, 10)
    turtle.done()


main()
